package com.wuwangfu.utils;

import ch.hsr.geohash.GeoHash;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @Description：
 * @Author：jcshen
 * @Date：2023-07-03
 */
public class GeoUtils {

    public static final String key = "";

    public static String[] getAreaInfoByLongitudeAndLatitude(HttpClient httpClient, Jedis jedis, double longitude, double latitude) {
        String province = "";
        String city = "";
        String district = "";
        String bizNames = "";

        try {
            //将经纬度使用GEOHash进行编码
            GeoHash geoHash = GeoHash.withCharacterPrecision(latitude, longitude, 8);
            String base32Code = geoHash.toBase32();
            //根据geoHash编码，到redis中进行查找
            String areaInfo = jedis.get(base32Code);
            //{wx4sqk42 -> 省,市,区|商圈1,商圈2}
            //如果有就关联地理信息和商圈信息
            if (areaInfo != null) {
                String[] fields = areaInfo.split("[|]");
                String area = fields[0];
                //判断是否有商圈
                if (fields.length > 1) {
                    bizNames = fields[1];
                }
                String[] pcd = area.split(",");
                province = pcd[0];
                city = pcd[1];
                district = pcd[2];
            } else {
                //如果没有查到，就通过httpClient请求高德地图API；通过外网调用高德地图API，构造一个get对象
                GetMethod getMethod = new GetMethod("https://restapi.amap.com/v3/geocode/regeo?key=" + key + "&location=" + longitude + "," + latitude);
                //发送请求
                int status = httpClient.executeMethod(getMethod);
                if (status == 200) {
                    //获取请求的json字符串
                    String jsonStr = getMethod.getResponseBodyAsString();
                    //转成json对象
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    //获取位置信息
                    JSONObject regeocode = jsonObj.getJSONObject("regeocode");
                    if (regeocode != null && !regeocode.isEmpty()) {
                        JSONObject address = regeocode.getJSONObject("addressComponent");
                        //获取省市区、商圈
                        province = address.getString("province");
                        city = address.getString("city");
                        district = address.getString("district");

                        ArrayList<String> lb = new ArrayList<String>();
                        //商圈数组（多个）
                        JSONArray businessAreas = address.getJSONArray("businessAreas");
                        for (int i = 0; i < businessAreas.size(); i++) {

                            JSONObject businessArea = null;

                            try {
                                businessArea = businessAreas.getJSONObject(i);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (businessArea != null) {
                                String businessName = businessArea.getString("name");
                                String longitudeAndLatitude = businessArea.getString("location");

                                String[] fds = longitudeAndLatitude.split(",");

                                lb.add(businessName);

                                //将商圈的经纬度使用GeoHash进行编码
                                GeoHash geohash = GeoHash.withCharacterPrecision(Double.parseDouble(fds[1]), Double.parseDouble(fds[0]), 8);
                                //将地理位置信息和商圈信息更新到redis中；更新完善本地商圈知识库；将查询处理的商圈的实际信息保存到redis
                                jedis.set(geohash.toBase32(), province + "," + city + "," + district + "|" + businessName);
                            }
                        }

                        bizNames = StringUtils.join(lb.toArray(), ",");
                        jedis.set(base32Code, province + "," + city + "," + district + "|" + bizNames);
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new String[]{province, city, district, bizNames};
    }
}
